package com.shunhao.utils;

import android.app.Activity;

import java.util.LinkedList;
import java.util.List;

/**
 * <pre>
 * 文件名：	BaseAppManager
 * 作　者：	康贵阳
 * 时　间：	2018/3/14 14:55
 * 描　述：   管理Activity
 * @author
 * </pre>
 */
public class BaseAppManager {

    private static BaseAppManager instance = null;
    private static List<Activity> mActivities = new LinkedList<>();

    /**
     * 私有构造函数
     */
    private BaseAppManager() {
    }

    /**
     * 双重检查单例模式
     *
     * @return activity管理对象
     */
    public static BaseAppManager getInstance() {
        if (null == instance) {
            synchronized (BaseAppManager.class) {
                if (null == instance) {
                    instance = new BaseAppManager();
                }
            }
        }
        return instance;
    }

    public int size() {
        return mActivities.size();
    }

    public synchronized Activity getForwardActivity() {
        return size() > 0 ? mActivities.get(size() - 1) : null;
    }

    public synchronized void addActivity(Activity activity) {
        mActivities.add(activity);
    }

    public synchronized void removeActivity(Activity activity) {
        mActivities.remove(activity);
    }

    public synchronized void clear() {
        for (int i = mActivities.size() - 1; i > -1; i--) {
            Activity activity = mActivities.get(i);
            removeActivity(activity);
            activity.finish();
            i = mActivities.size();
        }
    }


    public synchronized void clearToTop() {
        for (int i = mActivities.size() - 2; i > -1; i--) {
            Activity activity = mActivities.get(i);
            removeActivity(activity);
            activity.finish();
            i = mActivities.size() - 1;
        }
    }
}
